import React, { useState } from 'react'
import { InfiniteLoading, PullToRefresh } from '@nutui/nutui-react-taro'
import type { InfinityRenderPropType } from './type'

const CustomInfinityRenderComponent: React.FC<InfinityRenderPropType> = (props) => {
  const mainRender = () => {
    if (props.isNeedPullRefresh) {
      return (
        <PullToRefresh style={props.pullRefreshStyle} onRefresh={() => refreshFunc()} renderIcon={(status) => renderIcon(status)}>
          <InfiniteLoading target="scroll" hasMore={props.hasMore} onLoadMore={() => onLoadMore()} loadingText={loadingText()} loadMoreText={loadingMoreText()}>
            {props.children}
          </InfiniteLoading>
        </PullToRefresh>
      )
    } else {
      return <></>
    }
  }
  const [limit, setLimit] = useState<number>(() => {
    return props.limit ?? 10
  })
  const [size, setSize] = useState<number>(() => {
    return props.size ?? 1
  })
  const refreshFunc = async () => {
    setLimit(props.limit ?? 1)
    setSize(props.size ?? 10)
    await props.init(limit, size)
    if (props.onRefresh) {
      return props.onRefresh()
    } else {
      return Promise.resolve('done')
    }
  }
  const renderIcon = (status: any): React.ReactNode => {
    if (status === 'pulling' || status === 'complete') {
      return <>{status}</>
    } else if (status === 'canRelease' || status === 'refreshing') {
      return <>{status}</>
    }
    return <></>
  }
  const loadingText = (): React.ReactNode => {
    if (props.loadingText) {
      return props.loadingText()
    }
    return <>加载中...</>
  }
  const loadingMoreText = (): React.ReactNode => {
    if (props.loadMoreText) {
      return props.loadMoreText()
    }
    return <>没有更多了</>
  }

  const onLoadMore = () => {
    setSize(limit + 1)
    return props.init(limit, size)
  }
  return mainRender()
}

export default CustomInfinityRenderComponent
